package com.example.xd.model_video.videoeditlib.editVideoPlay;

import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class EncryptionUtil {

    private static final String TAG = EncryptionUtil.class.getSimpleName();
    private static Encryptor encryptor;
    private static Decryptor decryptor;

    static {
        encryptor = new Encryptor();
        try {
            decryptor = new Decryptor();
        } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException e) {
            e.printStackTrace();
        }
    }

    public static String decryptText(String alias, byte[] encryption, byte[] iv) {
        try {
            return decryptor
                    .decryptData(alias, encryption, iv);
        } catch (UnrecoverableEntryException | NoSuchAlgorithmException |
                KeyStoreException | NoSuchPaddingException | NoSuchProviderException |
                IOException | InvalidKeyException e) {
            Log.e(TAG, "decryptData() called with: " + e.getMessage(), e);
        } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Nullable
    public static Encryptor.ByteData encryptText(String alias, String text) {

        try {
            return encryptor
                    .encryptText(alias, text);
        } catch ( NoSuchAlgorithmException | NoSuchProviderException |
                IOException | NoSuchPaddingException | InvalidKeyException e) {
            Log.e(TAG, "onClick() called with: " + e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException |
                IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static String restorePW(String alias, String pw){
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
////            return encryptText(alias, pw);
//        }
//        return "";
//    }
//
//    public static String getPW(String alias, String encryption, byte[] iv){
//        return decryptText(alias, encryption, iv);
//    }
}
